package com.frank.big.feignClient;

import com.frank.big.util.SHA1;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.openfeign.FeignFormatterRegistrar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 小石潭记
 * @date 2020/10/23 10:03
 * @Description: ${todo} FeignFormatterRegistrar  不知道干嘛的
 */
@Configuration
public class BidataOnlineFeignConfig implements FeignFormatterRegistrar, RequestInterceptor {

    private List<Formatter> formatterList = new ArrayList<>();

    /**
     *  这里统一配置接口的header
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 时间撮 如果使用System.currentTimeMillis 高并发会有性能问题
        String currentTimestamp = String.valueOf(ZonedDateTime.now().toInstant().toEpochMilli());
        int randomInt = (int) ((Math.random() * 9 + 1) * 100000);
        String nonce = String.valueOf(randomInt);
        String securityKey = "T1YAEGbDOz7tIzq5cxff91jqG4PBtB75dY7IKcfqNS8ev0jYSJwtU4RSyqhQO8b9";
        String uid = "7W03RFHF";
        String signature = SHA1.encrypt(nonce + ";" + securityKey + ";" + currentTimestamp + ";" + uid + ";");
        requestTemplate.header("Content-Type", "application/json");
        requestTemplate.header("X-Uid", uid);
        requestTemplate.header("X-Timestamp", currentTimestamp);
        requestTemplate.header("X-Nonce", nonce);
        requestTemplate.header("X-Signature", signature);

    }

    /**
     *  todo 看下这里的作用
     * @param formatterRegistry
     */
    @Override
    public void registerFormatters(FormatterRegistry formatterRegistry) {
        if (formatterList.size() != 0) {
            formatterList.forEach(formatterRegistry::addFormatter);
        }
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有，根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }

}
